import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Table, Icon, Popover, Checkbox, Button, Modal, Row, Col, Input, Select, Spin } from 'antd';
import Chooser from 'components/chooser'
const FormItem = Form.Item;

import invoiceService from 'components/template/select-invoice-title-modal/select-invoice-title.service'
import 'styles/components/template/select-invoice-title-modal/select-invoice-title-modal.scss'

class SelectInvoiceTitleModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      btnLoading: false,
      editInvoiceTitle: false,
      cityFetching: false,
      areaFetching: false,
      columns: [
        {title: messages('common-1.key550')/*发票抬头*/, dataIndex: 'invoiceTitle', render: value => (
          <Popover content={value}>{value}</Popover>
        )},
        {title: messages('common-1.key551')/*企业税号*/, dataIndex: 'taxNumber', render: value => (
          <Popover content={value}>{value}</Popover>
        )},
        {title: messages('common-1.key552')/*银行账号*/, dataIndex: 'bankAccount', width: '10%', render: value => (
            <Popover content={value}>{value}</Popover>
          )},
        {title: messages('common-1.key553')/*开户行*/, dataIndex: 'bankBranchName', width: '10%', render: value => (
            <Popover content={value}>{value}</Popover>
          )},
        {title: messages('common-1.key554')/*电话*/, dataIndex: 'enterpriseMobile', width: '10%', render: value => (
            <Popover content={value}>{value}</Popover>
          )},
        {title: messages('common-1.key555')/*地址*/, dataIndex: 'enterpriseAddress', width: '10%', render: value => (
            <Popover content={value}>{value}</Popover>
          )},
        {title: messages('common.operation')/*操作*/, dataIndex: 'id', width: '10%', render: (value, record) => (
          <a onClick={() => this.handleEditInvoice(record)}>{messages('common.update')/*修改*/}</a>
        )}
      ],
      invoiceData: [],
      provinces:[],
      cities:[],
      areas: [],
      selectedRowKeys: [],
      page: 0,
      size: 5,
      pagination: {
        total: 0
      },
      selectedInfo: null,
      editInvoiceTitleInfo: {},
    }
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.selectedInvoiceOID !== nextProps.selectedInvoiceOID) {
      this.setState({
        selectedRowKeys: [nextProps.selectedInvoiceOID],
      });
    }
    if (nextProps.visible && !this.state.invoiceData.length) {
      if(!this.state.editInvoiceTitle)
        this.getList();
    }
  }

  //获取发票抬头信息
  getList = () => {
    const { page, size, selectedRowKeys } = this.state;
    let params = { page, size };
    this.setState({ loading: true });
    invoiceService.getInvoiceTile(params).then(res => {
      res.data.map(item => {
        if(item.id === selectedRowKeys[0]){
          this.setState({
            selectedInfo: item,
          })
        }
      });
      this.setState({
        loading: false,
        invoiceData: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({ page: page - 1 }, () => {
        this.getList(false)
      })
  };

  //操作 - 修改
  handleEditInvoice = (record) => {
    this.props.form.resetFields();
    this.setState({
      editInvoiceTitle: true,
      editInvoiceTitleInfo: record
    })
  };

  //取消
  onCancel = () => {
    if (this.state.editInvoiceTitle) {
      Modal.confirm({
        title: messages('common-1.key556')/*确定放弃编辑中的发票信息吗*/,
        onOk: () => {
          this.setState({ editInvoiceTitle: false });
          this.props.onCancel()
        },
      })
    } else {
      this.props.onCancel()
    }
  };

  //确定
  onOk = () => {
    const {editInvoiceTitle, selectedInfo, selectedRowKeys} = this.state;
    if (editInvoiceTitle) {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          const { editInvoiceTitleInfo } = this.state;
          (editInvoiceTitleInfo.id) && (values.id = editInvoiceTitleInfo.id);
          (values.bankId) && (values.bankBranchName = values.bankId[0].bankBranchName);
          (values.bankId) && (values.bankId = values.bankId[0].id);
          invoiceService.addInvoiceTitle(values, !values.id).then((res) => {
            if(res.status === 200) {
              this.setState({ editInvoiceTitle: false, btnLoading: false }, ()=>{this.getList()})
            } else {
              this.setState({ btnLoading: false })
            }
          });
        }
      })
    } else {
      this.props.onOk(selectedInfo || {});
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, btnLoading, editInvoiceTitle, cityFetching, areaFetching, columns, invoiceData, provinces, cities, areas, selectedRowKeys,
      pagination, editInvoiceTitleInfo, selectedInfo} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16, offset: 1}
    };
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: selectedRowKeys => this.setState({selectedRowKeys}),
      onSelect: record => this.setState({selectedInfo: record})
    };
    let dom =  document.getElementsByClassName('select-invoice-title-modal');
    let con = dom && dom.length ? dom[0] :  document.getElementById('select-invoice-modal');
    return (
      <div>
        <div className="select-invoice-title-modal"/>
        <Modal visible={this.props.visible}
               width={800}
               title={messages('common-1.key557')/*选择开票信息*/}
               getContainer={() => dom[0]}
               onCancel={this.onCancel}
               onOk={this.onOk}
        >
          <Table rowKey='id'   //需要修改
                 loading={loading}
                 dataSource={invoiceData}
                 columns={columns}
                 rowSelection={rowSelection}
                 pagination={pagination}
                 bordered
                 size='middle'
          />
          <Button type='primary'
                  style={pagination.total ? {marginBottom: '20px'} : {margin: '20px 0'}}
                  onClick={() => this.setState({editInvoiceTitle: true, editInvoiceTitleInfo: {}, cities: [], areas: []})}>
            <Icon type="plus-circle-o" />{messages('common-1.key558')/*新建开票信息*/}
          </Button>
          {editInvoiceTitle && (
            <Form>
              <FormItem {...formItemLayout} label={messages('common-1.key550')/*发票抬头*/} colon={false}>
                {getFieldDecorator('invoiceTitle', {
                  rules: [{
                    required: true,
                    message: messages('common-1.key225')/*请输入temp2*/
                  }],
                  initialValue: editInvoiceTitleInfo.invoiceTitle
                })(
                  <Input placeholder={messages('common-1.key225')/*请输入temp2*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('common-1.key551')/*企业税号*/} colon={false}>
                {getFieldDecorator('taxNumber', {
                  rules: [{
                    required: true,
                    message: messages('common-1.key225')/*请输入temp2*/
                  }],
                  initialValue: editInvoiceTitleInfo.taxNumber
                })(
                  <Input placeholder={messages('common-1.key225')/*请输入temp2*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('common-1.key552')/*银行账号*/} colon={false}>
                {getFieldDecorator('bankAccount', {
                  initialValue: editInvoiceTitleInfo.bankAccount
                })(
                  <Input placeholder={messages('common-1.key225')/*请输入temp2*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('common-1.key553')/*开户行*/} colon={false}>
                {getFieldDecorator('bankId', {
                  initialValue: editInvoiceTitleInfo.bankId ? [{bankBranchName: editInvoiceTitleInfo.bankBranchName, id: editInvoiceTitleInfo.bankId}] : undefined
                })(
                  <Chooser single={true}
                           type="select_bank"
                           locale={{emptyText: messages('common-1.key1311')/*当前条件没有搜索到银行，建议分词以提高搜索命中率，例：【工商银行深圳华侨城支行】改为【工商银行 深圳 华侨城支行】*/}}
                           placeholder={messages('common-1.key52')/*请选择temp*/}
                           labelKey="bankBranchName"
                           valueKey="id"/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('common-1.key554')/*电话*/} colon={false}>
                {getFieldDecorator('enterpriseMobile', {
                  initialValue: editInvoiceTitleInfo.enterpriseMobile
                })(
                  <Input placeholder={messages('common-1.key225')/*请输入temp2*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('common-1.key555')/*地址*/} colon={false}>
                {getFieldDecorator('enterpriseAddress', {
                  initialValue: editInvoiceTitleInfo.enterpriseAddress
                })(
                  <Input placeholder={messages('common-1.key225')/*请输入temp2*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label=" " colon={false}>
                {getFieldDecorator("default", {
                  valuePropName: 'checked',
                  initialValue: editInvoiceTitleInfo.default
                })(
                  <Checkbox>{messages('common-1.key16')/*设为默认*/}</Checkbox>
                )}
              </FormItem>
            </Form>
          )}
        </Modal>
      </div>
    )
  }
}

SelectInvoiceTitleModal.propTypes = {
  visible: React.PropTypes.bool.isRequired,
  selectedOID: React.PropTypes.string, //已选择的地址id
  onCancel: React.PropTypes.func,
  onOk: React.PropTypes.func,
};

SelectInvoiceTitleModal.defaultProps={
  onCancel: () => {},
  onOk: () => {},
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

const WrappedSelectInvoiceTitleModal = Form.create()(SelectInvoiceTitleModal);

export default connect(mapStateToProps)(WrappedSelectInvoiceTitleModal)
